

package TransportesMarroquin;

import com.mysql.jdbc.Connection;

import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import javax.sound.sampled.Clip; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.awt.Color;
import java.awt.Toolkit;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioSystem;
import javax.swing.JOptionPane;

/**
 *
 * @author mYnOr
 */
public class LlantasCamion extends javax.swing.JFrame {
javax.sound.sampled.Clip sonido;
    int[] num = new int[8]; // arreglo de numeros
   int resultado;
   int codpaquete;
   boolean error = false;
   boolean completo = false;
   int codcam=0;
   Limitador limdd = new Limitador(11);
   Limitador limdi = new Limitador(11);
   Limitador limtd = new Limitador(11);
   Limitador limti = new Limitador(11);
    /** Creates new form LlantasCamion */
    public LlantasCamion(int cod) {
        initComponents();
        this.codcam=cod;

    dd.setDocument(limdd);
    di.setDocument(limdi);
    td.setDocument(limtd);
    ti.setDocument(limti);
    }

    private LlantasCamion() {
        
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dd = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        di = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        td = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        ti = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 204, 204));

        dd.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ddKeyTyped(evt);
            }
        });

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ImagenLlanta.png"))); // NOI18N

        di.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                diKeyTyped(evt);
            }
        });

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ImagenLlanta.png"))); // NOI18N

        jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ImagenLlanta.png"))); // NOI18N

        td.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tdKeyTyped(evt);
            }
        });

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ImagenLlanta.png"))); // NOI18N

        ti.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tiKeyTyped(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/aceptar.png"))); // NOI18N
        jButton1.setText("Insertar ");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        jButton3.setText("Cancerlar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/regresar.png"))); // NOI18N
        jButton2.setText("Regresar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(143, 0, 0));

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel13.setForeground(new java.awt.Color(255, 255, 255));
        jLabel13.setText("Nuevo Camion                        - LLantas -");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel13)
                .addContainerGap(61, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel13)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(di, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ti, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(dd)
                            .addComponent(td, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jButton3))
                .addGap(31, 31, 31))
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 185, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ti, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(di, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(49, 49, 49)
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(dd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(49, 49, 49)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(td, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
error=false;
        IngresarLlantas();

if (error==false){
    
     LlenarPacketeN();
}

if(completo==true){
            
            IngresarPaqueteACamion();
            Camion.nc.dispose();
            dispose();
            Camion va;
       
            va = new Camion();
            va.setVisible(true);
             va.setBounds(114, 107, Toolkit.getDefaultToolkit().getScreenSize().width-114, Toolkit.getDefaultToolkit().getScreenSize().height-107);
      
} // fin del if de completo


    }//GEN-LAST:event_jButton1ActionPerformed
  public void  IngresarPaqueteACamion (){
        try {
            MysqlDataSource dataSource = new MysqlDataSource();
               dataSource.setUser("root");
               dataSource.setPassword("");
               dataSource.setDatabaseName("practicasp8");
               dataSource.setServerName("localhost");
               Connection conexion = (Connection) dataSource.getConnection();
               Statement instruccion;
               
               instruccion=(Statement) conexion.createStatement();
               instruccion.executeUpdate("update camion set idpaquetecamion='"+ codpaquete+"' where idcamion="+codcam);
        } catch (SQLException ex) {
             JOptionPane.showMessageDialog(rootPane, "Error:"+ex);

        }
    }
    
    
    
 public void IngresarLlantas (){

     try {

            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setUser("root");
            dataSource.setPassword("");
            dataSource.setDatabaseName("practicasp8");
            dataSource.setServerName("localhost");
          Connection  conexion = (Connection) dataSource.getConnection();

            Statement instruccion;
            ResultSet rs;
            instruccion = (Statement) conexion.createStatement();
                  

 // LLANTA UNO
            try {
                     num[0]=Integer.parseInt(di.getText());
                }catch (Exception e){
                    JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta delantera izquiera, no és un dato númerico  ");

                }

             if(error==false){
            try{
                 instruccion.executeUpdate("insert into llanta (idnumeconomico,tipo_vehiculo,codigo_vehiculo,posicion) values('" + num[0] + "','Camion','"+codcam+"','Llanta delantera izquierda')",Statement.RETURN_GENERATED_KEYS); // me sirve para obter el id de llanta uno
            }catch (Exception e ){
                error=true;
                GeneracionError();
                di.setText(""+"Error");
                di.setBackground(Color.red);
                JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta delantera izquierda''"+num[0] +"'' número economico ya existente\n"+e);
            }
          
            }





// LLANTA DOS
    try {
                     num[1]=Integer.parseInt(dd.getText());
                }catch (Exception e){
                    JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta delantera derecha, no és un valor númerico.  ");

                }
   if(error==false){
            try{
                 instruccion.executeUpdate("insert into llanta (idnumeconomico,tipo_vehiculo,codigo_vehiculo,posicion) values('" + num[1] + "','Camion','"+codcam+"','Llanta delantera derecha')",Statement.RETURN_GENERATED_KEYS); // me sirve para obter el id de llanta uno
            }catch (Exception e ){
                error=true;
                GeneracionError();
                dd.setText(""+"Error");
                dd.setBackground(Color.red);
                JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta delantera derecha''"+num[1] +"'' número economico ya existente\n"+e);
            }
          
            }



//LLANTA TRES

           try {
                     num[2]=Integer.parseInt(ti.getText());
                }catch (Exception e){
                    JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta trasera izquierda, no és un vaolor númerico");

                }

         if(error==false){
            try{
                 instruccion.executeUpdate("insert into llanta (idnumeconomico,tipo_vehiculo,codigo_vehiculo,posicion) values('" + num[2] + "','Camion','"+codcam+"','Llanta trasera izquierda')",Statement.RETURN_GENERATED_KEYS); // me sirve para obter el id de llanta uno
            }catch (Exception e ){
                error=true;
                GeneracionError();
                ti.setText(""+"Error");
                ti.setBackground(Color.red);
                JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta trasera izquierda''"+num[2] +"'' número economico ya existente\n"+e);
            }
          
            }



// LLANTA CUATRO
             try {
                     num[3]=Integer.parseInt(td.getText());
                }catch (Exception e){
                    JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta trasera derecha, no és un valor númerico");

                }

             if(error==false){
            try{
                 instruccion.executeUpdate("insert into llanta (idnumeconomico,tipo_vehiculo,codigo_vehiculo,posicion) values('" + num[3] + "','Camion','"+codcam+"','Llanta trasera derecha')",Statement.RETURN_GENERATED_KEYS); // me sirve para obter el id de llanta uno
            }catch (Exception e ){
                error=true;
                GeneracionError();
                td.setText(""+"Error");
                td.setBackground(Color.red);
                JOptionPane.showMessageDialog(rootPane, "Dato erroneo en la llanta trasera derecha''"+num[3] +"'' número economico ya existente\n"+e);
            }
          
            }



         

               conexion.close(); // cierro la conexion


             }catch(SQLException e){

            System.out.println("EXCEPCION EN Base de Datos:"+e.toString());
           } // fin del catch

   }



   public void LlenarPacketeN (){
       {

     try {
           
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setUser("root");
            dataSource.setPassword("");
            dataSource.setDatabaseName("practicasp8");
            dataSource.setServerName("localhost");
             // coneccion
            Connection conexion = (Connection) dataSource.getConnection();
            
            PreparedStatement ps = null;
            ResultSet rs;

            ps = (PreparedStatement) conexion.prepareStatement("insert into paquetecamion (di,dd,ti,td) values (?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);

            try {
                 ps.setInt(1,num[0]);
            }catch(Exception e){
                   JOptionPane.showMessageDialog(rootPane, "Dato erroneo Revisar Manual  ");

           } // fin del catch

  // LLANTA DOS



            try {
                 ps.setInt(2,num[1]);
            }catch(Exception e){
                   JOptionPane.showMessageDialog(rootPane, "Dato erroneo Revisar Manual  ");

           } // fin del catch

//LANTA TRES

            try {
                 ps.setInt(3,num[2]);
            }catch(Exception e){
                   JOptionPane.showMessageDialog(rootPane, "Dato erroneo Revisar Manual  ");

           } // fin del catch
 // LLANTA CUATRO


            try {
                 ps.setInt(4,num[3]);
            }catch(Exception e){
                   JOptionPane.showMessageDialog(rootPane, "Dato erroneo Revisar Manual  ");

           } // fin del catch
             resultado = ps.executeUpdate();
            
             rs = ps.getGeneratedKeys();
              System.out.println(" "+rs);
            while (rs.next()) {
                codpaquete = rs.getInt(1);
                
                }

// sonido
 completo=true;

try
{
  sonido = null;
  sonido=AudioSystem.getClip();
  sonido.open(AudioSystem.getAudioInputStream(new File(System.getProperty ("user.dir")+"\\src\\SonidosPractica\\Correcto2.wav")));
  sonido.start();




}catch(Exception e)
  {System.out.println(""+e);} // fin

            JOptionPane.showMessageDialog(rootPane, "Dato ingresado exitosamente");
             
               conexion.close(); // cierro la conexion
               ps.close();

             }catch(SQLException e){

           
              JOptionPane.showMessageDialog(rootPane, "Dato en la base de datos \n :"+e.toString());
            
           } // fin del catch
    
   }

   }
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
        Camion.nc.dispose();
        Error.Mysql("delete from camion where idcamion="+codcam);
        Camion va;
       
            va = new Camion();
            va.setVisible(true);
             va.setBounds(114, 107, Toolkit.getDefaultToolkit().getScreenSize().width-114, Toolkit.getDefaultToolkit().getScreenSize().height-107);
       
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        NuevoCamion.va.dispose();
        Camion.nc.show();
        Error.Mysql("DELETE from camion where idcamion = "+NuevoCamion.enviarcod);
}//GEN-LAST:event_jButton2ActionPerformed

    private void diKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_diKeyTyped
        char c = evt.getKeyChar();
       if(!(Character.isDigit(c))|| c== evt.VK_BACK_SPACE || c==evt.VK_DELETE){
           getToolkit().beep();
           evt.consume();
       }
    }//GEN-LAST:event_diKeyTyped

    private void tiKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tiKeyTyped
         char c = evt.getKeyChar();
       if(!(Character.isDigit(c))|| c== evt.VK_BACK_SPACE || c==evt.VK_DELETE){
           getToolkit().beep();
           evt.consume();
       }
    }//GEN-LAST:event_tiKeyTyped

    private void ddKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ddKeyTyped
        char c = evt.getKeyChar();
       if(!(Character.isDigit(c))|| c== evt.VK_BACK_SPACE || c==evt.VK_DELETE){
           getToolkit().beep();
           evt.consume();
       }
    }//GEN-LAST:event_ddKeyTyped

    private void tdKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tdKeyTyped
          char c = evt.getKeyChar();
       if(!(Character.isDigit(c))|| c== evt.VK_BACK_SPACE || c==evt.VK_DELETE){
           getToolkit().beep();
           evt.consume();
       }
    }//GEN-LAST:event_tdKeyTyped

   public void GeneracionError (){
        try {
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setUser("root");
            dataSource.setPassword("");
            dataSource.setDatabaseName("practicasp8");
            dataSource.setServerName("localhost");
            Connection conexion = (Connection) dataSource.getConnection();
            Statement instruccion;

            instruccion = (Statement) conexion.createStatement();
            for(int i=0; i!=8;i++){
               instruccion.executeUpdate("DELETE from llanta where idnumeconomico = "+num[i]+" AND codigo_vehiculo ="+codcam+" AND tipo_vehiculo LIKE 'Camion'");
               
            }
            conexion.close();
            instruccion.close();
        } catch (SQLException ex) {
            Logger.getLogger(LlantasFurgon.class.getName()).log(Level.SEVERE, null, ex);
           
        }
  }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LlantasCamion().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dd;
    private javax.swing.JTextField di;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField td;
    private javax.swing.JTextField ti;
    // End of variables declaration//GEN-END:variables

}
